package com.lc.config;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    // Step3
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        // 设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);
        /**
         * 添加Shrio的内置过滤器：
         * anon：无需认证即可访问
         * authc：必须认证才能访问
         * user：必须有记住我才能访问
         * perms：拥有对某个资源的权限才能访问
         * role：拥有某个角色权限
         */
        // 设置权限
        Map<String, String> filterMap = new LinkedHashMap<>();

        // 授权，没有授权会跳到401
        // filterMap.put("/user","perms[super]");

        // 拦截
        filterMap.put("/user","authc");
        filterMap.put("/car/*","authc");
        filterMap.put("/shop/*","authc");
        filterMap.put("/order/*","authc");
        bean.setFilterChainDefinitionMap(filterMap);

        // 设置登陆请求
        bean.setLoginUrl("/toLogin");
        // 设置未授权的请求
        bean.setUnauthorizedUrl("/noauth");


        return bean;
    }
    // Step2
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 关联UserRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }
    // Step1
    // 创建ream对象，需要自定义类
    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }

}
